package com.sndscl.rpc;

import com.alibaba.fastjson.JSONObject;
import com.sndscl.rpc.common.constant.SndSclConstant;
import com.sndscl.rpc.common.util.NetWorkInterfaceUtils;
import com.sndscl.rpc.common.util.ZookeeperClient;
import com.sndscl.rpc.netty.SndsclNettyServer;
import com.sndscl.rpc.spring.SndSclBeanPostProcessor;
import com.sndscl.rpc.spring.SpringApplicationContextUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.springframework.core.env.Environment;

import java.io.IOException;
import java.util.Set;

/**
 * @Description
 * @Author lsh
 * @Date 2020/10/14 15:10
 **/
public class SandSculptureServer {

    private int port = 10001;

    public void init() throws IOException, KeeperException, InterruptedException {
        Environment environment = SpringApplicationContextUtils.getEnvironment();
        String zkUrl = environment.getProperty(SndSclConstant.SPRING_PRO_ZK__NAME);
        String servicePort = environment.getProperty(SndSclConstant.SPRING_PRO_SERVICE_PORT);
        if(zkUrl == null && "".equals(zkUrl)){
            System.err.println("SndScl RPC INIT ERROR,PROPERTY "+zkUrl+"  isEmpty！");
            return;
        }
        if(servicePort != null && !"".equals(servicePort)){
            port = Integer.valueOf(servicePort);
        }

        String hostIp = null;
        try {
            hostIp = NetWorkInterfaceUtils.getLocalHostLANAddress().getHostAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(hostIp == null){
            System.err.println("GET LOCAL IP ADDRESS ERROR! CHECK YOU IP CONFIG");
            return;
        }
        //注册接口信息
        Set<String> interfaces = SndSclBeanPostProcessor.getInterfaceList();
        ZookeeperClient zookeeperClient = new ZookeeperClient();
        zookeeperClient.connection(zkUrl);
        //创建根节点
        zookeeperClient.createNode(SndSclConstant.ROOT_PATH,"", CreateMode.PERSISTENT);

        if(StringUtils.isNotBlank(hostIp)){
            //发布本服务的接口
            zookeeperClient.createNode(SndSclConstant.ROOT_PATH +"/"+hostIp+":"+port,JSONObject.toJSONString(interfaces),CreateMode.EPHEMERAL);
            System.out.println("发布接口：\n"+interfaces);
        }
        //启动 RPC 服务
        SndsclNettyServer sndsclNettyServer = new SndsclNettyServer();
        sndsclNettyServer.startService(port);
    }
}
